﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using TechTree.Stalk.Roots;
using TechTree.Stalk.Roots.Cache;
using TechTree.Stalk.Roots.Configuration.Components;
using TechTree.Stalk.Roots.Exceptions;
using TechTree.Stalk.Roots.Globalization.Interfaces;
using TechTree.Stalk.Roots.Logging;

namespace TechTree.Stalk.Roots.Globalization
{
    /// <summary>
    /// Component used for internationalization that centralizes access to sources of dictionary and provides access to information in the application of current culture.
    /// </summary>
    public static class Globalization
    {
        #region Constantes

        private const string CACHE_GROUP = "globalization";
        private const string CACHE_SEPARATOR = "@";

        private const string DEFAULT_CULTURE = "pt-BR";
        private const string GLOBALIZATION_DEFAULT_LOG_TITLE = "Globalization";

        private const string ERROR_MESSAGE_ARGUMENT_NULL_KEY = "The entered key is null or empty.";
        private const string ERROR_MESSAGE_CULTURE_STARTUP = "An error occurred while starting up culture '{0}'.";
        private const string ERROR_MESSAGE_CULTURE_SOURCE_DICTIONARY = "An error occurred while initializing the source dictionary '{0}'.";
        private const string ERROR_MESSAGE_CULTURE_SOURCE_DICTIONARY_NULL_OR_EMPTY = "No source dictionary was informed.";
        private const string ERROR_MESSAGE_SEARCH_TEXT_DICTIONARY = "An error occurred while searching text '{0}' in the dictionary.";
        private const string ERROR_MESSAGE_SEARCH_CACHE = "An error occurred while searching text in the cache. Key '{0}'.";
        private const string ERROR_MESSAGE_SET_CACHE_INFO = "An error occurred while writing text in the cache. Key '{0}'.";

        private const string INFO_MESSAGE_PARAMETER_STARTUP = "The Globalization component will be initialized in the culture '{0}', with the Globalization component with key '{1}'.";
        private const string INFO_MESSAGE_STARTUP_ACTUAL_CULTURE = "The culture '{0}' is now active in Globalization component.";

        #endregion

        #region Inicialization

        /// <summary>
        /// Initializes the Globalization, according to the parameters specified.
        /// </summary>
        /// <param name="culture_">Culture being used by Globalization.</param>
        /// <param name="sourceDictionaryConfigurationKey_">The full class name of the source dictionary to be used by Globalization.</param>
        public static void Startup(string culture_, string sourceDictionaryConfigurationKey_)
        {
            Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, string.Format(INFO_MESSAGE_PARAMETER_STARTUP, culture_, sourceDictionaryConfigurationKey_), Category.Execution, Severity.Information);

            StartupCulture(culture_, false);
            StartupSourceDictionary(sourceDictionaryConfigurationKey_);
        }

        private static void StartupCulture(string culture_, bool changeUserCulture_)
        {
            if (!string.IsNullOrEmpty(culture_))
            {
                try
                {
                    CurrentCulture = new CultureInfo(culture_, changeUserCulture_);
                }
                catch (ArgumentException argEx)
                {
                    Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, string.Format(ERROR_MESSAGE_CULTURE_STARTUP, culture_), Category.Execution, Severity.Error, argEx);
                }
            }

            //If can not start the culture, uses the current culture in the application
            if (CurrentCulture == null)
            {
                CurrentCulture = new CultureInfo(DEFAULT_CULTURE, changeUserCulture_);
            }

            Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, string.Format(INFO_MESSAGE_STARTUP_ACTUAL_CULTURE, CurrentCulture.Name), Category.Execution, Severity.Information);
        }

        private static void StartupSourceDictionary(string sourceDictionaryClass_)
        {
            if (!string.IsNullOrEmpty(sourceDictionaryClass_))
            {
                try
                {
                    ComponentElement component = ComponentsConfiguration.GetConfig().Globalization[sourceDictionaryClass_];

                    CurrentSourceDictionary = Factory<ISourceDictionary>.CreateInstance(component.Class);
                }
                catch (Exception ex)
                {
                    Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, string.Format(ERROR_MESSAGE_CULTURE_SOURCE_DICTIONARY, sourceDictionaryClass_), Category.Execution, Severity.Error, ex);
                }
            }
            else
            {
                Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, ERROR_MESSAGE_CULTURE_SOURCE_DICTIONARY_NULL_OR_EMPTY, Category.Execution, Severity.Error);
            }
        }

        #endregion

        #region Static Properties

        private static ISourceDictionary CurrentSourceDictionary
        {
            get;
            set;
        }

        /// <summary>
        ///Represents the cultural current used by Globalization
        /// </summary>
        public static CultureInfo CurrentCulture
        {
            get;
            private set;
        }

        #endregion

        #region Métodos Estáticos

        /// <summary>
        /// Returns the text read out from the dictionary identified by the informed key.
        /// </summary>
        /// <param name="key_">Text Identifier</param>
        /// <returns>The text contained in the dictionary.</returns>
        public static string GetString(string key_)
        {
            return GetString(key_, CurrentCulture);
        }

        /// <summary>
        /// Returns the text read out from the dictionary identified by the informed key and culture.
        /// </summary>
        /// <param name="key_">Text Identifier</param>
        /// <param name="cultureInfo_">Culture-specific for search in the dictionary.</param>
        /// <returns>The text contained in the dictionary.</returns>
        public static string GetString(string key_, CultureInfo cultureInfo_)
        {
            if (string.IsNullOrEmpty(key_))
            {
                throw new GlobalizationException(ERROR_MESSAGE_ARGUMENT_NULL_KEY);
            }

            //declaração para evitar alteração do valor informado
            CultureInfo validCulture = cultureInfo_;

            if (validCulture == null)
            {
                validCulture = CurrentCulture;
            }

            try
            {
                string valor = GetStringCache(key_, validCulture);

                //TODO: Check the best way to get things from cache
                if (string.IsNullOrEmpty(valor))
                {
                    if (CurrentSourceDictionary != null)
                    {
                        valor = CurrentSourceDictionary.GetText(key_, validCulture);
                        StoreStringCache(key_, valor, validCulture);
                    }
                }

                return valor;
            }
            catch (Exception ex)
            {
                Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, string.Format(ERROR_MESSAGE_SEARCH_TEXT_DICTIONARY, key_), Category.Execution, Severity.Error, ex);
                throw new Exception(string.Format(ERROR_MESSAGE_SEARCH_TEXT_DICTIONARY, key_), ex);
            }
        }

        #endregion

        #region Globalization Caching

        private static string GetStringCache(string key_, CultureInfo culture_)
        {
            string texto = null;

            try
            {
                return Cache.Cache.Instance.Get<String>(new CacheKey(CACHE_GROUP, key_ + CACHE_SEPARATOR + culture_.ToString()));
            }
            catch (Exception ex)
            {
                Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, string.Format(ERROR_MESSAGE_SEARCH_CACHE, key_), Category.Execution, Severity.Information, ex);
            }

            return texto;
        }

        private static void StoreStringCache(string key_, string text_, CultureInfo culture_)
        {
            try
            {
                CacheKey cacheKey = new CacheKey(CACHE_GROUP, key_ + CACHE_SEPARATOR + culture_.ToString());

                if (!Cache.Cache.Instance.HasKey(cacheKey))
                    Cache.Cache.Instance.Include<String>(cacheKey, text_);
            }
            catch (Exception ex)
            {
                Log.Write(GLOBALIZATION_DEFAULT_LOG_TITLE, string.Format(ERROR_MESSAGE_SET_CACHE_INFO, key_), Category.Execution, Severity.Information, ex);
            }
        }

        #endregion
    }
}
